package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate RedisTemplate;

    @Override
    public Result sendcode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号不符合格式");
        }
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到Redis
        RedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.模拟发送验证码
        log.info("发送验证码到:" + phone + "验证码为：" + code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验验证码
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            Result.fail("手机号不符合格式");
        }
        //2.比较验证码是否正确
        //获取正确的验证码和前端提交过来的验证码进行对比
        String code = loginForm.getCode();
        //从redis中获取正确的验证码和前端提交的进行对比
        String rightCode = RedisTemplate.opsForValue().get(LOGIN_CODE_KEY+loginForm.getPhone());
        if (code == null || !rightCode.equals(code)){
            Result.fail("验证码不正确");
        }
        //3.根据手机号取数据库中查询用户是否粗在
        User user = query().eq("phone", loginForm.getPhone()).one();
        //4.判断用户是否存在 如果user为null则代表不存在
        if (user == null){
            //用户不存在则创建对应的用户
            user = CreateUserWithByPhone(loginForm.getPhone());
        }
        //5.将用户信息使用hash存入到redis中
        String token = UUID.randomUUID().toString();
        Map<String, Object> userMap = BeanUtil.beanToMap(user, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        RedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token,userMap);
        //设置过期时间并返回token
        RedisTemplate.expire(LOGIN_USER_KEY + token,30,TimeUnit.SECONDS);
        return Result.ok(token);
    }

    @Override
    public Result queryUserById(Long userId) {
        User user = getById(userId);
        if (user == null){
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    @Override
    public Result sign() {
        //1. 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2. 获取当天日期
        LocalDate now = LocalDate.now();
        //2.1 解析当天日期时间格式
        String KeySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        //3. 拼接key
        String key = USER_SIGN_KEY + userId + KeySuffix;
        //4 获取当月中的第几天
        int dayOfMonth = now.getDayOfMonth();
        RedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1 用户id
        Long userId = UserHolder.getUser().getId();
        //2 获取当前时间
        LocalDate now = LocalDate.now();
        String KeySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        String key = USER_SIGN_KEY + userId + KeySuffix;
        // 一个月中的第几天
        int dayOfMonth = now.getDayOfMonth();
        List<Long> result = RedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        while (true){
            if ((num & 1) == 0) {
                // 未签到 停止循环
                break;
            }else {
                // 计数器加1
                count++;
            }
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private User CreateUserWithByPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
